using SqlSugar;

namespace Digitalmes.Application.Common.Extensions;

/// <summary>
/// 针对于 <see cref="ISugarQueryable{}"/> 对象扩展。
/// </summary>
public static class ISugarQueryablePagationExtensions
{
    /// <summary>
    /// 分页查询。
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="query"></param>
    /// <param name="pageNumber">页号</param>
    /// <param name="pageSize">每页数量</param>
    /// <param name="cancellationToken"></param>
    /// <returns></returns>
    public static async Task<PagedList<T>> GetPagedListAsync<T>(this ISugarQueryable<T> query,
        int pageNumber, int pageSize, CancellationToken cancellationToken = default)
        where T : class, new()
    {
        RefAsync<int> totalNumber = 0;
        var items = await query.ToPageListAsync(pageNumber, pageSize, totalNumber, cancellationToken);
        return new PagedList<T>
        {
            Items = items,
            Total = totalNumber,
            TotalPages = (int)Math.Ceiling(totalNumber / (double)pageSize),
        };
    }
}
